/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.utils;

import java.io.IOException;
import java.io.OutputStream;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Breno Leite
 */
public class WebUtils {

    /**
     * Sends a file to the client through a request.
     *
     * @param bytes the file bytes to be sended
     * @param fileName the name of the file
     * @param mimeType the mime type of the file
     * @param facesContext current faces context
     */
    public static synchronized void downloadFileFromBytes(byte[] bytes,
            String fileName, String mimeType, FacesContext facesContext) {
        ExternalContext context = facesContext.getExternalContext();
        HttpServletResponse httpServletResponse = (HttpServletResponse) context.getResponse();
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        httpServletResponse.setContentLength(bytes.length);
        httpServletResponse.setContentType(mimeType);

        try {
            OutputStream outputStream = httpServletResponse.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            facesContext.responseComplete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
